package com.yq.core.service.impl;

import com.yq.api.exception.product.AddProductException;
import com.yq.core.dao.ProductDao;
import com.yq.core.dto.ProductDO;
import com.yq.core.po.ProductQueryPO;
import com.yq.core.service.ProductService;
import com.yq.core.util.DOUtil;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by yq on 16-8-7.
 */
@Stateless(name = "productService")
public class ProductServiceImpl implements ProductService {
    @PersistenceContext(unitName = "mallJPAUnit")
    private EntityManager entityManager;

    @EJB(name = "productDaoImpl")
    private ProductDao productDao;
    /**
     *新建产品
     * */
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public ProductDO addProduct(ProductDO productDO) {
        if(productDO == null){
            throw new AddProductException("productDO参数为空，无法添加产品");
        }
        DOUtil.completeUserDateInfo(productDO);
        entityManager.persist(productDO);
        return productDO;
    }

    public ProductDO getProductByProductId(Long productId) {
        if(productId == null || productId.longValue() < 0){
            return null;
        }
        return entityManager.find(ProductDO.class, productId);
    }

    /**
     * 查询多个产品
     * */
    public List<ProductDO> queryProducts(ProductQueryPO productQueryPO) {
        if(productQueryPO == null) {
            return null;
        }

        return productDao.queryProduct(productQueryPO);
    }
}
